package com.mazaiting.screen.picture

import android.annotation.TargetApi
import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.graphics.Bitmap
import android.media.projection.MediaProjectionManager
import android.os.Build
import android.os.Bundle
import android.os.IBinder
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.mazaiting.log.L
import com.mazaiting.screen.R
import com.mazaiting.screen.util.FileUtil
import com.mazaiting.widget.view.FloatView
import kotlinx.android.synthetic.main.activity_picture.*


/***
 *
 *
 *                                                    __----~~~~~~~~~~~------___
 *                                   .  .   ~~//====......          __--~ ~~
 *                   -.            \_|//     |||\\  ~~~~~~::::... /~
 *                ___-==_       _-~o~  \/    |||  \\            _/~~-
 *        __---~~~.==~||\=_    -_--~/_-~|-   |\\   \\        _/~
 *    _-~~     .=~    |  \\-_    '-~7  /-   /  ||    \      /
 *  .~       .~       |   \\ -_    /  /-   /   ||      \   /
 * /  ____  /         |     \\ ~-_/  /|- _/   .||       \ /
 * |~~    ~~|--~~~~--_ \     ~==-/   | \~--===~~        .\
 *          '         ~-|      /|    |-~\~~       __--~~
 *                      |-~~-_/ |    |   ~\_   _-~            /\
 *                           /  \     \__   \/~                \__
 *                       _--~ _/ | .-~~____--~-/                  ~~==.
 *                      ((->/~   '.|||' -_|    ~~-/ ,              . _||
 *                                 -_     ~\      ~~---l__i__i__i--~~_/
 *                                 _-~-__   ~)  \--______________--~~
 *                               //.-~~~-~_--~- |-------~~~~~~~~
 *                                      //.-~~~--\
 *                               神兽保佑
 *                              代码无BUG!
 * @author mazaiting
 * @date 2019-07-23
 * @description 截屏父类
 */
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
class ScreenActivity : AppCompatActivity() {
    companion object {
        /**
         * 请求媒体工程码
         */
        private const val REQUEST_MEDIA_PROJECTION = 0x100


        /**
         * 开启截屏页面
         * @param context 上下文
         */
        fun newInstance(context: Context) {
            val intent = Intent(context, ScreenActivity::class.java)
            // 新的任务栈
            intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
            context.startActivity(intent)
        }
    }

    /**
     * 照片服务
     */
    private var mPictureService: ScreenService? = null
    /**
     * 媒体工程管理者
     */
    private var mMediaProjectionManager: MediaProjectionManager? = null

    /**
     * 绑定服务连接工具
     */
    private val mConnection = object : ServiceConnection {
        override fun onServiceConnected(className: ComponentName, service: IBinder) {
            // 获取服务
            val binder = service as ScreenService.PictureBinder
            // 设置图片服务
            mPictureService = binder.service
        }

        override fun onServiceDisconnected(className: ComponentName) {}
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_picture)

        L.d("ScreenActivity--onCreate")

        initView()

        // 创建媒体工程管理者
        mMediaProjectionManager =
            application.getSystemService(Context.MEDIA_PROJECTION_SERVICE) as MediaProjectionManager
        // 检测权限
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Toast.makeText(this, "请开启悬浮窗权限", Toast.LENGTH_LONG).show()
            startOverlayPermission()
        }
    }

    /**
     * 初始化 View
     */
    private fun initView() {
        // 开启截屏
        screen_btn_start.setOnClickListener {
            // 绑定截图服务
            val intent = Intent(this, ScreenService::class.java)
            bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
            // 请求截屏
            screenShot()
        }
        // 结束截屏
        screen_btn_stop.setOnClickListener {
            super.onBackPressed()
        }
    }

    /**
     * 开启悬浮权限
     */
    private fun startOverlayPermission() {
        // 判断是否有悬浮窗权限
        if (!FloatView.checkFloatPermission(this)) {
            FloatView.startPermissionActivity(this, 0)
        }
    }

    /**
     * 截屏
     */
    private fun screenShot() {
        startActivityForResult(mMediaProjectionManager!!.createScreenCaptureIntent(), REQUEST_MEDIA_PROJECTION)
    }

    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
//        L.d("requestCode: $requestCode, resultCode: $resultCode, data: $data")
        if (requestCode == REQUEST_MEDIA_PROJECTION) {
            // 判断请求码和数据
            if (data != null && resultCode != 0) {
                dealData(resultCode, data)
                quitApplication()
            } else {
                Toast.makeText(this@ScreenActivity, "请允许截取您的屏幕上所有的内容!", Toast.LENGTH_SHORT).show()
            }
        }
    }

    /**
     * 处理数据
     * @param resultCode 结果码
     * @param data 视图数据
     */
    private fun dealData(resultCode: Int, data: Intent?) {
        // 创建媒体管理者
        val mediaProjection = mMediaProjectionManager?.getMediaProjection(resultCode, data)
        // 设置
        mPictureService?.setMediaProjection(mediaProjection!!)
        // 开始截图
        mPictureService?.setPictureListener(object : ScreenService.IPictureListener {
            override fun onBitmap(bitmap: Bitmap) {
                // 图片名
                val imageName = FileUtil.getFileName(this@ScreenActivity)
                // 保存
                val isSuccess = FileUtil.saveBitmap(bitmap, imageName)
                // 检测是否成功
                if (isSuccess) {
                    Toast.makeText(this@ScreenActivity, "截图成功", Toast.LENGTH_SHORT).show()
                } else {
                    Toast.makeText(this@ScreenActivity, "截图失败", Toast.LENGTH_SHORT).show()
                }
            }
        })
    }

    /**
     * 退出应用, 点击返回键不退出应用
     */
    private fun quitApplication() {
        val home = Intent(Intent.ACTION_MAIN)
        home.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
        home.addCategory(Intent.CATEGORY_HOME)
        startActivity(home)
    }

    override fun onBackPressed() {
//        super.onBackPressed()
        quitApplication()
    }

    override fun onDestroy() {
        L.d("ScreenActivity--onDestroy")
        unbindService(mConnection)
        mPictureService = null
        super.onDestroy()
    }
}
